Structure.js ➔ ???   A
last analyzed

Complexity

Conditions 1
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
nc 2
nop 2
dl 0
loc 6
cc 1
rs 9.4285
1
const mkdirp = require('mkdirp');
2
const path = require('path');
3
const fs = require('fs');
4
const structureSchema = require('../sample/folder-schema');
5
const baseDir = require('./baseDir');
6
7
/**
8
 * Define and build the application folder structure
9
 * @class Structure
10
 */
11
class Structure {
12
13
  /**
14
   * Creates an instance of Structure.
15
   * @param {string} extend - path to add to current working drectory
16
   * @param {any} schema - folder structure schema
17
   * @memberOf Structure
18
   */
19
  constructor(extend = '', schema) {
20
    this.schema = schema || structureSchema;
21
    this.filepath = `${baseDir.getCurrentWorkingDir()}/${extend}`;
22
    this.mainpath = path.join(__dirname, '../');
23
    this.appname = '';
24
  }
25
26
  /**
27
   * Move through the folder schema and create folders and files
28
   * @param {Array} dir - current directory to iterate through
29
   * @param {Array} pathname - contains each individual parent
30
   * folders name
31
   * @returns {Void} returns nothing
32
   * @memberOf Structure
33
   */
34
  traverse(dir, pathname) {
35
    if (!pathname) {
36
      pathname = [];
37
    }
38
    dir.forEach((root, index, parent) => {
39
      if (typeof root === 'object') {
40
        pathname.push(Object.keys(root)[0]);
41
        mkdirp.sync(
42
          path.join(
43
            this.filepath,
44
            `${pathname.join('/')}`));
45
        this.traverse(root[Object.keys(root)[0]], pathname);
46
      } else {
47
        let template = fs.readFileSync(
48
          path.join(this.mainpath, `/sample/${root}.sample`))
49
          .toString();
50
        if (root === 'index.html') {
51
          template = template.replace('(title)', this.appname);
52
        }
53
        fs.writeFile(
54
          path.join(
55
            this.filepath,
56
            `${pathname.join('/')}/${root}`),
57
          template);
58
        if (index === parent.length - 1) {
59
          pathname.pop();
60
        }
61
      }
62
    });
63
  }
64
65
  /**
66
   * Build the folder structure based off the provided schema
67
   * @param {String} name - name of react app to create
68
   * @returns {Promise} resolves promise when directories have been created
69
   * @memberOf Structure
70
   */
71
  build(name) {
72
    this.appname = name;
73
    return new Promise((resolve) => {
74
      this.traverse(this.schema);
75
      if (baseDir.directoryExists(
76
        path.join(
77
          this.filepath, '/test/mocha-helper.js'))) {
78
        resolve(this.schema);
79
      }
80
    });
81
  }
82
}
83
84
module.exports = Structure;
85